package com.rookie.session.filter.util;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static RedisTemplate<String, Object> staticRedisTemplate;

    @PostConstruct
    public void init() {
        staticRedisTemplate = this.redisTemplate;
    }

    /**
     * 设置缓存
     *
     * @param key   key名称
     * @param value 值
     * @return 操作结果
     */
    public static boolean set(String key, Object value) {
        try {
            staticRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 覆盖值不更新过期时间
     *
     * @param key   key
     * @param value value
     * @return 结果
     */
    public static boolean setOverride(String key, Object value) {
        try {
            staticRedisTemplate.opsForValue().set(key, value, 0);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存
     *
     * @param key   key名称
     * @param value 值
     * @param time  时间/秒 必须大于0
     * @return 结果
     */
    public static boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                staticRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存
     *
     * @param key   key名称
     * @param value 值
     * @param time  时间、单位根据unit来判断
     * @param unit  时间类型
     * @return 结果
     */
    public static boolean set(String key, Object value, long time, TimeUnit unit) {
        try {
            if (time > 0) {
                staticRedisTemplate.opsForValue().set(key, value, time, unit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param keys key列表
     * @return 结果
     */
    public static boolean del(String... keys) {
        if (keys != null && keys.length > 0) {
            Long deleteSize = staticRedisTemplate.delete(Arrays.asList(keys));
            return deleteSize != null && deleteSize > 0;
        }
        return false;
    }

    /**
     * 删除缓存
     *
     * @param pattern 模糊key
     * @return 结果
     */
    public static int patternDel(String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            Set<String> keyList = batchGetKey(pattern);
            if (keyList.size() < 1) {
                return 0;
            }
            Long result = staticRedisTemplate.delete(keyList);
            return result == null ? 0 : result.intValue();
        }
        return 0;
    }

    /**
     * 获取缓存
     *
     * @param key key的名称
     * @return 缓存值
     */
    public static Object get(String key) {
        return key == null ? null : staticRedisTemplate.opsForValue().get(key);
    }

    public static <T> List<T> batchGet(List<String> keyList, Class<T> clazz) {
        if (ObjectUtils.isEmpty(keyList)) {
            return null;
        }
        List<Object> resultTmp = staticRedisTemplate.opsForValue().multiGet(keyList);
        if (resultTmp != null) {
            return JsonUtils.getListObject(resultTmp.stream().filter(Objects::nonNull).collect(Collectors.toList()), clazz);
        }
        return null;
    }

    public static <T> List<T> batchGet(String pattern, Class<T> clazz) {
        Set<String> keys = batchGetKey(pattern);
        if (keys.size() < 1){
            return new ArrayList<>();
        }
        return batchGet(new ArrayList<>(keys),clazz);
    }

    public static String getString(String key) {
        if (key == null) {
            return null;
        }
        try {
            return (String) staticRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Integer getInteger(String key) {
        if (key == null) {
            return null;
        }
        try {
            return (Integer) staticRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定类型的缓存
     *
     * @param key   key
     * @param clazz 类型
     * @return 结果
     */
    public static <T> T get(String key, Class<T> clazz) {
        if (key == null) {
            return null;
        }
        try {
            return JsonUtils.getObject(staticRedisTemplate.opsForValue().get(key), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定集合类型的缓存
     *
     * @param key   key
     * @param clazz 类型
     * @return 结果
     */
    public static <T> List<T> getList(String key, Class<T> clazz) {
        if (key == null) {
            return null;
        }
        try {
            return JsonUtils.getListObject(staticRedisTemplate.opsForValue().get(key), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置缓存失效时间
     *
     * @param key  key名称
     * @param time 时间/秒
     * @return 结果
     */
    public static boolean expire(String key, long time) {
        try {
            if (time > 0) {
                staticRedisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存失效时间
     *
     * @param key  key
     * @param time 时间
     * @param unit 时间类型
     * @return 结果
     */
    public static boolean expire(String key, long time, TimeUnit unit) {
        try {
            if (time > 0) {
                staticRedisTemplate.expire(key, time, unit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取缓存的失效时间
     *
     * @param key key
     * @return 秒，如果是-1则是永久，null则表示不存在
     */
    public static Long getExpire(String key) {
        return staticRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断是否存在key
     *
     * @param key key
     * @return 结果
     */
    public static boolean hasKey(String key) {
        try {
            Boolean result = staticRedisTemplate.hasKey(key);
            if (result != null) {
                return result;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean nonAndSet(String key, long time) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        // 指定 lua 脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/duplicateRequest.lua")));
        // 指定返回类型
        redisScript.setResultType(Long.class);
        // 参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Long result = staticRedisTemplate.execute(redisScript, Collections.singletonList(key), time);
        if (result == null) {
            return false;
        }
        return result.equals(0L);
    }


    /**
     * @param key    key
     * @param maxNum 最大值
     * @return key自增后的数值
     */
    public static int increaseAndGet(String key, String maxNum) {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/increaseAndGet.lua")));
        // 指定返回类型
        redisScript.setResultType(Long.class);
        Long result = staticRedisTemplate.execute(redisScript, Arrays.asList(key, maxNum));
        if (result == null) {
            return -1;
        }
        return result.intValue();

    }



    public static boolean leftPush(String key, Object value) {
        Long num = staticRedisTemplate.opsForList().leftPush(key, value);
        return num != null;
    }

    public static Object leftPop(String key) {
        return staticRedisTemplate.opsForList().leftPop(key);
    }

    public static <T> List<T> rangeDataOfList(String key, int startIndex, int endIndex, Class<T> clazz) {
        List<Object> range = staticRedisTemplate.opsForList().range(key, startIndex, endIndex);
        return JsonUtils.getListObject(range, clazz);
    }

    public static long getListSize(String key) {
        Long size = staticRedisTemplate.opsForList().size(key);
        return size == null ? 0 : size;
    }

    public static Set<String> batchGetKey(String pattern) {
        Set<String> keys = staticRedisTemplate.keys(pattern);
        if (keys == null || keys.size() < 1) {
            return new HashSet<>();
        }
        return keys;
    }

    public static void rename(String oldName,String newName){
        staticRedisTemplate.rename(oldName,newName);
    }
}